﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.Bill.PlugIn.Args;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LiMinCRMPlugin
{
    /// <summary>
    /// 
    /// </summary>
    /// <remarks>
    /// 功能：
    /// 创建人：张虎
    /// 创建日期：2024/3/21 9:21:58
    /// </remarks>
    /// 
    [Description("调拨申请单中选择物料将其组织间计算价目表的金额反写过来")]
    [HotUpdate]
    public class TransferApplySaveEdit : AbstractBillPlugIn
    {
        public override void BeforeSave(BeforeSaveEventArgs e)
        {
            base.BeforeSave(e);
            if (Convert.ToString(this.View.Model.GetValue("F_QLTK_Combo_tzk")) == "2" && Convert.ToString(this.View.Model.GetValue("FTRANSTYPE")) == "OverOrgTransfer")
            {

                EntryEntity entryEntity = this.View.BusinessInfo.GetEntryEntity("FEntity");//表体名称
                DynamicObjectCollection entryRows = this.View.Model.GetEntityDataObject(entryEntity);//取得新增加行的行号
                foreach (DynamicObject entryRow in entryRows)//循环单据体遍历
                {
                    string MATERIALID = entryRow["MATERIALID_Id"].ToString();//物料
                    string FStockOrgId = entryRow["STOCKORGID_Id"].ToString();//调出组织
                    double F_QLTK_SL = double.Parse(entryRow["F_QLTK_SL"].ToString());//税率
                    double FBASEQTY = double.Parse(entryRow["BASEQTY"].ToString());//申请数量
                    double FQty = double.Parse(entryRow["QTY"].ToString());//申请数量
                    double shuilv = 1 + F_QLTK_SL / 100;
                    string sql = string.Format(@"select a.FNUMBER,b.FERPCLSID from T_BD_MATERIAL a
                                                        inner join T_BD_MATERIALBASE b on  a.FMATERIALID = b.FMATERIALID
                                                        where a.FMATERIALID='" + MATERIALID + "'");
                    DataTable sql_toStirng = DBUtils.ExecuteDataSet(this.Context, sql).Tables[0];
                    if (sql_toStirng.Rows.Count > 0)
                    {
                        //物料属性
                        string FERPCLSID = sql_toStirng.Rows[0]["FERPCLSID"].ToString();
                        //物料编码
                        string fnumber = sql_toStirng.Rows[0]["FNUMBER"].ToString();

                        //物料属性为自制
                        if (FERPCLSID.Equals("2")|| FERPCLSID.Equals("3"))
                        {
                            string sqls = string.Format(@"select FMATERIALID from T_BD_MATERIAL where FUSEORGID='" + FStockOrgId + "' and FNUMBER='"+ fnumber + "'");
                            DataTable sql_toStirngs = DBUtils.ExecuteDataSet(this.Context, sqls).Tables[0];
                            if (sql_toStirngs.Rows.Count>0) 
                            {
                                string fmatrid = sql_toStirngs.Rows[0]["FMATERIALID"].ToString();
                                //查询物料在组织间结算价目标中单据状态，行状态，是否否审核，是否在生效日和失效日期间
                                string sql1 = string.Format(@"/*dialect*/select * from T_IOS_PRICELIST a
                                                    inner join T_IOS_PRICELISTENTRY b on a.FID=b.FID
                                                    where a.FDOCUMENTSTATUS='C' and b.FROWAUDITSTATUS='A' 
                                                    and CONVERT(DATE, GETDATE()) BETWEEN a.FEFFECTIVEDATE AND a.FEXPIRYDATE
                                                    and CONVERT(DATE, GETDATE()) BETWEEN b.FEFFECTIVEDATE AND b.FEXPRIYDATE
                                                    and b.FMATERIALID='" + fmatrid + "' order by a.FCREATEDATE desc");
                                DataTable sql_toStirng1 = DBUtils.ExecuteDataSet(this.Context, sql1).Tables[0];
                                if (sql_toStirng1.Rows.Count > 0)
                                {
                                    double FPrice = 0;
                                    if (double.Parse(entryRow["F_RDLV_HSDJ"].ToString()) == 0)
                                    {
                                        FPrice = double.Parse(sql_toStirng1.Rows[0]["FPrice"].ToString());//不含税单价
                                        FPrice = FPrice*FBASEQTY/FQty;
                                    }
                                    else
                                    {
                                        FPrice = double.Parse(entryRow["F_RDLV_HSDJ"].ToString());
                                    }
                                    entryRow["F_RDLV_HSDJ"] = FPrice;
                                    double F_QLTK_Amount_qtr = FQty * FPrice;
                                    entryRow["F_QLTK_Amount_qtr"] = F_QLTK_Amount_qtr;
                                    entryRow["F_QLTK_TaxPrice"] = FPrice * shuilv;
                                    entryRow["F_QLTK_AllAmount"] = FPrice * shuilv * FQty;
                                }                            
                            
                            }
                        }
                        else if (FERPCLSID.Equals("1"))
                        {
                            DateTime now = DateTime.Now;
                            int currentYear = now.Year;
                           
                             //取调出组织的最后期初结存价格                            
                            string sql2 = string.Format(@"SELECT   
                                                            C.FFINORGID AS FORGID,  
                                                            M.FMASTERID,  
                                                            M.FNUMBER,  
                                                            O.FYEAR,  
                                                            O.FPERIOD,  
                                                            SUM(CASE  WHEN HB.FENDINITKEY = 0 THEN HB.FQTY ELSE 0 END) 期初数, 
	                                                        SUM(CASE  WHEN HB.FENDINITKEY = 0 THEN HB.FAMOUNT ELSE 0 END) 期初金额,
	                                                        SUM(CASE WHEN HB.FENDINITKEY=1 THEN HB.FQTY ELSE 0 END) AS 期末数,
	                                                        SUM(CASE WHEN HB.FENDINITKEY=1 THEN HB.FAMOUNT ELSE 0 END) AS 期末金额,
                                                            SUM(CASE WHEN HB.FENDINITKEY=1 THEN HB.FOUTSTOCKQTY ELSE 0 END) AS 出库数,
                                                            SUM(CASE WHEN HB.FENDINITKEY=1 THEN HB.FCURRENTOUTAMOUNT ELSE 0 END) AS 出库金额
                                                             FROM   
                                                                 T_HS_BALANCE HB  
                                                             LEFT JOIN T_HS_STOCKDIMENSION S ON HB.FDIMEENTRYID=S.FENTRYID  
                                                             LEFT JOIN T_HS_CALDIMENSIONS C ON HB.FDIMENSIONID=C.FDIMENSIONID  
                                                             LEFT JOIN T_HS_OUTACCTG O ON HB.FID=O.FID  
                                                             LEFT JOIN T_BD_MATERIAL M ON S.FMASTERID=M.FMASTERID AND C.FFINORGID=M.FUSEORGID  
                                                             LEFT JOIN T_ORG_ORGANIZATIONS_L L ON L.FORGID=C.FFINORGID AND L.FLOCALEID=2052  
                                                             LEFT JOIN T_BD_STOCK AS ST ON ST.FSTOCKID =S.FSTOCKID  
                                                             WHERE O.FYEAR='{0}' and m.FNUMBER='{1}' and C.FFINORGID='{2}'
                                                             GROUP BY C.FFINORGID, M.FMASTERID, O.FYEAR, O.FPERIOD, M.FNUMBER  ", currentYear, fnumber, FStockOrgId);
                            DataTable sql_toStirng2 = DBUtils.ExecuteDataSet(this.Context, sql2).Tables[0];
                            if (sql_toStirng2.Rows.Count > 0)
                            {
                                double FTaxPrice = 0;
                                if (double.Parse(entryRow["F_RDLV_HSDJ"].ToString()) == 0)
                                {
                                    if (double.Parse(sql_toStirng2.Rows[0]["期末数"].ToString()) == 0) 
                                    {
                                        if (double.Parse(sql_toStirng2.Rows[0]["出库数"].ToString()) == 0) 
                                        {
                                            FTaxPrice = 0;//期初金额
                                        }
                                        else
                                        {
                                            FTaxPrice = double.Parse(sql_toStirng2.Rows[0]["出库金额"].ToString()) / double.Parse(sql_toStirng2.Rows[0]["出库数"].ToString());
                                            FTaxPrice = FBASEQTY * FTaxPrice / FQty;
                                        }
                                    }
                                    else
                                    {
                                        FTaxPrice = double.Parse(sql_toStirng2.Rows[0]["期末金额"].ToString()) / double.Parse(sql_toStirng2.Rows[0]["期末数"].ToString());
                                        FTaxPrice = FBASEQTY * FTaxPrice / FQty;
                                    }
                                }
                                else
                                {
                                    FTaxPrice = double.Parse(entryRow["F_RDLV_HSDJ"].ToString());
                                }
                                entryRow["F_RDLV_HSDJ"] = FTaxPrice;
                                double F_QLTK_Amount_qtr = FQty * FTaxPrice;
                                entryRow["F_QLTK_Amount_qtr"] = F_QLTK_Amount_qtr;
                                entryRow["F_QLTK_TaxPrice"] = FTaxPrice * shuilv;
                                entryRow["F_QLTK_AllAmount"] = FTaxPrice * shuilv* FQty;
                                if (FTaxPrice == 0) 
                                {
                                    //调出组织的应付单价格
                                    string sql3 = string.Format(@"select b.FTAXPRICE,* from  T_AP_PAYABLE a 
                                                                    inner join T_AP_PAYABLEENTRY b on a.fid = b.fid
                                                                    where b.FMATERIALID='" + MATERIALID + "' and a.FSETTLEORGID='"+ FStockOrgId + "' and FSetAccountType='3'  order by a.FCREATEDATE desc");
                                    DataTable sql_toStirng3 = DBUtils.ExecuteDataSet(this.Context, sql3).Tables[0];
                                    if (sql_toStirng3.Rows.Count > 0)
                                    {
                                        double FTaxPrice1 = 0;
                                        if (double.Parse(entryRow["F_RDLV_HSDJ"].ToString()) == 0)
                                        {
                                            FTaxPrice1 = double.Parse(sql_toStirng3.Rows[0]["FTAXPRICE"].ToString());//含税单价
                                        }
                                        else
                                        {
                                            FTaxPrice1 = double.Parse(entryRow["F_RDLV_HSDJ"].ToString());
                                        }
                                        double F_QLTK_Amount_qtr1 = FQty * FTaxPrice1;
                                        entryRow["F_RDLV_HSDJ"] = FTaxPrice1;
                                        entryRow["F_QLTK_Amount_qtr"] = F_QLTK_Amount_qtr1;
                                        entryRow["F_QLTK_TaxPrice"] = FTaxPrice1 * shuilv;
                                        entryRow["F_QLTK_AllAmount"] = FTaxPrice1 * shuilv * FQty;

                                    }
                                    else
                                    {
                                        //调出组织的采购订单价格
                                        string sql4 = string.Format(@"select c.FTAXPRICE,* from  T_PUR_POORDER a 
                                                                        inner join T_PUR_POORDERENTRY b on a.fid = b.fid
                                                                        inner join T_PUR_POORDERENTRY_F c on b.FENTRYID = c.FENTRYID
                                                                        where b.FMATERIALID='" + MATERIALID + "'  and  a.FPURCHASEORGID='"+FStockOrgId+"' order by a.FCREATEDATE desc");
                                        DataTable sql_toStirng4 = DBUtils.ExecuteDataSet(this.Context, sql4).Tables[0];
                                        if (sql_toStirng4.Rows.Count > 0)
                                        {
                                            double FTaxPrice2 = 0;
                                            if (double.Parse(entryRow["F_RDLV_HSDJ"].ToString()) == 0)
                                            {
                                                FTaxPrice2 = double.Parse(sql_toStirng4.Rows[0]["FTAXPRICE"].ToString());//含税单价
                                            }
                                            else
                                            {
                                                FTaxPrice2 = double.Parse(entryRow["F_RDLV_HSDJ"].ToString());
                                            }
                                            double F_QLTK_Amount_qtr2 = FQty * FTaxPrice2;
                                            entryRow["F_RDLV_HSDJ"] = FTaxPrice2;
                                            entryRow["F_QLTK_Amount_qtr"] = F_QLTK_Amount_qtr2;
                                            entryRow["F_QLTK_TaxPrice"] = FTaxPrice2 * shuilv;
                                            entryRow["F_QLTK_AllAmount"] = FTaxPrice2 * shuilv * FQty;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                //调出组织的应付单价格
                                string sql3 = string.Format(@"select b.FTAXPRICE,* from  T_AP_PAYABLE a 
                                                                    inner join T_AP_PAYABLEENTRY b on a.fid = b.fid
                                                                    where b.FMATERIALID='" + MATERIALID + "' and a.FSETTLEORGID='"+ FStockOrgId + "' and FSetAccountType='3' order by a.FCREATEDATE desc");
                                DataTable sql_toStirng3 = DBUtils.ExecuteDataSet(this.Context, sql3).Tables[0];
                                if (sql_toStirng3.Rows.Count > 0)
                                {
                                    double FTaxPrice = 0;
                                    if (double.Parse(entryRow["F_RDLV_HSDJ"].ToString()) == 0)
                                    {
                                        FTaxPrice = double.Parse(sql_toStirng3.Rows[0]["FTAXPRICE"].ToString());//含税单价
                                    }
                                    else
                                    {
                                        FTaxPrice = double.Parse(entryRow["F_RDLV_HSDJ"].ToString());
                                    }
                                    double F_QLTK_Amount_qtr = FQty * FTaxPrice;
                                    entryRow["F_RDLV_HSDJ"] = FTaxPrice;
                                    entryRow["F_QLTK_Amount_qtr"] = F_QLTK_Amount_qtr;
                                    entryRow["F_QLTK_TaxPrice"] = FTaxPrice * shuilv;
                                    entryRow["F_QLTK_AllAmount"] = FTaxPrice * shuilv * FQty;
                                }
                                else
                                {
                                    //调出组织的采购订单价格
                                    string sql4 = string.Format(@"select c.FTAXPRICE,* from  T_PUR_POORDER a 
                                                                        inner join T_PUR_POORDERENTRY b on a.fid = b.fid
                                                                        inner join T_PUR_POORDERENTRY_F c on b.FENTRYID = c.FENTRYID
                                                                        where b.FMATERIALID='" + MATERIALID + "' and a.FPURCHASEORGID='"+FStockOrgId+"'   order by a.FCREATEDATE desc");
                                    DataTable sql_toStirng4 = DBUtils.ExecuteDataSet(this.Context, sql4).Tables[0];
                                    if (sql_toStirng4.Rows.Count > 0)
                                    {
                                        double FTaxPrice = 0;
                                        if (double.Parse(entryRow["F_RDLV_HSDJ"].ToString()) == 0)
                                        {
                                            FTaxPrice = double.Parse(sql_toStirng3.Rows[0]["FTAXPRICE"].ToString());//含税单价
                                        }
                                        else
                                        {
                                            FTaxPrice = double.Parse(entryRow["F_RDLV_HSDJ"].ToString());
                                        }
                                        double F_QLTK_Amount_qtr = FQty * FTaxPrice;
                                        entryRow["F_RDLV_HSDJ"] = FTaxPrice;
                                        entryRow["F_QLTK_Amount_qtr"] = F_QLTK_Amount_qtr;
                                        entryRow["F_QLTK_TaxPrice"] = FTaxPrice * shuilv;
                                        entryRow["F_QLTK_AllAmount"] = FTaxPrice * shuilv * FQty;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
